using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using NLog;
using NLog.Web;
using ReZero;
using zhwy.saas.api.Configurations;
using zhwy.saas.api.Extensions;
using zhwy.saas.api.Extensions.Converters;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Extensions.Services;
using zhwy.saas.api.Middleware;
using zhwy.saas.api.Services;
using zhwy.saas.api.Services.Sinterface;

var builder = WebApplication.CreateBuilder(args);

// 配置 NLog
LogManager.Setup().LoadConfigurationFromFile("nlog.config");
builder.Host.UseNLog();
// Add HTTP context accessor
builder.Services.AddHttpContextAccessor();
// Add services to the container.
builder.Services.AddControllers().AddJsonOptions(configure =>
{
    configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
    configure.JsonSerializerOptions.Converters.Add(new NullableDatetimeJsonConverter());
});

// 注册基础服务
builder.Services.AddSingleton<ILogExt, LogExt>();
builder.Services.AddTransient<ITokenService, TokenService>();
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
// 注册基础服务Service
ServiceExtensions.AddServices(builder.Services);

// 添加 JWT 配置
var jwtConfig = builder.Configuration.GetSection("Jwt").Get<JwtConfig>();
builder.Services.AddSingleton(jwtConfig);

// API 版本和 Swagger 配置
builder.Services.AddApiVersioningSetup();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    // 添加 XML 文档
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    options.IncludeXmlComments(xmlPath);
});
builder.Services.ConfigureOptions<ConfigureSwaggerOptions>();

//mysql
var dbConfigs = SqlSugarSetup.CreateConnections(builder.Configuration);
SqlSugarSetup.AddSqlSugarSetup(builder.Services, dbConfigs);

//编码
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

#if DEBUG
builder.Services.AddReZeroServices(api =>
{
    api.EnableSuperApi();
});
#endif

// Kestrel配置
builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

builder.Services.AddCors(options =>
{
    var corsConfig = builder.Configuration.GetSection("Cors").Get<CorsConfig>();
    options.AddPolicy("CorsPolicy", builder =>
    {
        builder
            .WithOrigins(corsConfig.Origins.ToArray())
            .WithMethods(corsConfig.Methods.ToArray())
            .WithHeaders(corsConfig.Headers.ToArray())
            .AllowCredentials()
            .WithExposedHeaders("Content-Disposition");
    });
});

var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
        foreach (var description in provider.ApiVersionDescriptions)
        {
            options.SwaggerEndpoint(
                $"/swagger/{description.GroupName}/swagger.json",
                description.GroupName.ToUpperInvariant());
        }
    });
}

app.UseHttpsRedirection();
app.UseRouting();

// 启用静态文件访问
app.UseStaticFiles(); // 默认的wwwroot静态文件访问

// 确保wwwroot目录存在
var wwwrootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
if (!Directory.Exists(wwwrootPath))
{
    Directory.CreateDirectory(wwwrootPath);
}

// 配置额外的静态文件中间件，增强对图片文件的处理
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(wwwrootPath),
    RequestPath = "",
    OnPrepareResponse = ctx =>
    {
        // 添加缓存控制头，对图片类型设置更长的缓存时间
        if (ctx.File.Name.EndsWith(".jpg") || 
            ctx.File.Name.EndsWith(".jpeg") || 
            ctx.File.Name.EndsWith(".png") || 
            ctx.File.Name.EndsWith(".gif") || 
            ctx.File.Name.EndsWith(".webp"))
        {
            // 设置图片缓存为7天
            const int durationInSeconds = 60 * 60 * 24 * 7;
            ctx.Context.Response.Headers.Append(
                "Cache-Control", $"public,max-age={durationInSeconds}");
        }
    }
});

// 在中间件配置部分添加（放在 app.UseRouting() 之后，app.UseAuthorization() 之前）
app.UseCors("CorsPolicy");
app.UseAuthorization();

// 添加中间件（注意顺序）
app.UseMiddleware<JwtAuthenticationMiddleware>();
//app.UseMiddleware<RequestLoggingMiddleware>();
app.UseMiddleware<GlobalExceptionMiddleware>();

app.MapControllers();

app.Run();
